package com.hoshiicloud.vericenter.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.hoshiicloud.common.validate.annotations.Mobile;
import com.hoshiicloud.vericenter.config.SmsConfig;
import com.hoshiicloud.vericenter.entity.SysMessages;
import com.hoshiicloud.vericenter.result.Response;
import com.hoshiicloud.vericenter.service.ISysMessagesService;
import com.hoshiicloud.vericenter.service.SmsService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;

/**
 * 短信接口
 * TODO 改为多租户模式,租户需提供相应的配置参数
 */
@Api(value = "短信接口",tags = "短信接口")
@RestController
@RequestMapping("/sms")
@Validated
public class SmsController {

    @Autowired
    private SmsService smsService;

    @Autowired
    private ISysMessagesService sysMessagesService;

    @ApiOperation(value = "验证短信验证码")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "msgId",value = "短信id",dataType = "String", required = true,example = "123456789"),
            @ApiImplicitParam(name = "code",value = "验证码",dataType = "String", required = true,example = "123456")
    })
    @PostMapping("/check")
    public Response checkCode(@RequestParam String msgId,@RequestParam  String code){
        Response result=sysMessagesService.getDetail(msgId);
        if(result.isSuccess()){
            SysMessages msg=(SysMessages) result.getData();
            if(msg.getAvailable().equals(1)){
                if(LocalDateTime.now().isAfter(msg.getExpiresTime())){
                    //已超时,修改记录
                    msg.setAvailable(0);
                    sysMessagesService.updateDataById(msg);
                    return Response.failed("验证码已超时");
                }
                else{
                    //code比较
                    if(msg.getRandCode().equals(code)){
                        msg.setAvailable(0);
                        sysMessagesService.updateDataById(msg);
                        return Response.success("验证成功");
                    }
                    else{
                        return Response.failed("验证码错误");
                    }
                }
            }
            else{
                return Response.failed("验证码已失效");
            }
        }
        else{
            return result;
        }
    }

    @ApiOperation(value = "发送短信验证码",notes = "发送成功data返回短信id")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "mobile",value = "短信id",dataType = "String", required = true,example = "123456789"),
            @ApiImplicitParam(name = "code",value = "验证码",dataType = "String", required = true,example = "123456"),
            @ApiImplicitParam(name = "expSecond",value = "有效时间(单位:秒)",dataType = "long", required = true,example = "60")
    })
    @PostMapping("/sendCode")
    public Response<String> sendCode(@RequestParam @Mobile String mobile, @RequestParam String code, @RequestParam long expSecond){
        //验证码模板ID 测试写固定
        String tplId="2201802";
        Response result= smsService.sendCode(mobile,code,tplId, SmsConfig.SYS_API_KEY);
        //如果短信发送成功插入一条记录
        if(result.isSuccess()){
            //TODO 计算短信费用
            LocalDateTime expTime= LocalDateTime.now().plusSeconds(expSecond);
            SysMessages entity=new SysMessages();
            //类别  1- 验证类  2-通知类
            entity.setType(1);
            entity.setRandCode(code);
            entity.setMobile(mobile);
            entity.setExpiresTime(expTime);
            //TODO 根据模版拼接内容
            entity.setContext("测试模板短信验证码,根据模板获得内容尚未实现");
            //是否有效  0-失效 1-有效
            entity.setAvailable(1);
            return sysMessagesService.insert(entity);
        }
        return result;
    }


    @ApiOperation(value="发送模板短信")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "mobile",value = "要发送的手机号码",dataType = "String", required = true),
            @ApiImplicitParam(name = "tplValue",value = "模板参数值,json字符串格式",dataType = "String", required = true),
            @ApiImplicitParam(name = "tplId",value = "短信模板id",dataType = "String", required = true)
    })
    @PostMapping("/sendTplMsg")
    public Response sendTplMsg(@RequestParam @Mobile String mobile, @RequestParam String tplValue, @RequestParam String tplId){
        String type="single";
        JSONObject jsonObject=JSONObject.parseObject(tplValue);
        Map<String,String> tplValueMap=JSON.parseObject(tplValue,Map.class);
        Response result= smsService.sendTplMsg(mobile,tplId,tplValueMap,type,SmsConfig.SYS_API_KEY);
        //如果短信发送成功插入记录
        if(result.isSuccess()){
            //TODO 计算短信费用

            LocalDateTime expTime= LocalDateTime.now();
            SysMessages entity=new SysMessages();
            //类别  1- 验证类  2-通知类
            entity.setType(2);
            entity.setMobile(mobile);
            entity.setExpiresTime(expTime);
            //TODO 根据模版拼接内容
            entity.setContext("测试模板短信,根据模板获得内容尚未实现");
            //是否有效  0-失效 1-有效
            entity.setAvailable(1);
            return sysMessagesService.insert(entity);
        }
        return result;
    }

    @ApiOperation(value="批量发送模板短信")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "mobile",value = "要发送的手机号码",dataType = "String", required = true),
            @ApiImplicitParam(name = "tplValue",value = "模板参数值,json字符串格式",dataType = "String", required = true),
            @ApiImplicitParam(name = "tplId",value = "短信模板id",dataType = "String", required = true)
    })
    @PostMapping("/batchSendTplMsg")
    public Response batchSendTplMsg(@RequestParam String mobile,@RequestParam String tplValue,@RequestParam String tplId){
        String type="batch";
        JSONObject jsonObject=JSONObject.parseObject(tplValue);
        Map<String,String> tplValueMap=JSON.parseObject(tplValue,Map.class);
        Response result= smsService.sendTplMsg(mobile,tplId,tplValueMap,type,SmsConfig.SYS_API_KEY);
        //如果短信发送成功插入记录
        // TODO 批量插入记录
        if(result.isSuccess()){
            //TODO 计算短信费用
            List<String> mobileList= Arrays.asList(mobile.split(","));
            List<SysMessages> list=new ArrayList<SysMessages>();
            for (int i=0;i<mobileList.size();i++){
                SysMessages entity=new SysMessages();
                LocalDateTime expTime= LocalDateTime.now();
                //暂时调用idworker
                entity.setId(IdWorker.getId());
                //类别  1- 验证类  2-通知类
                entity.setType(2);
                entity.setMobile(mobileList.get(i));
                entity.setExpiresTime(expTime);
                entity.setSentTime(LocalDateTime.now());
                //TODO 根据模板拼接内容
                entity.setContext("测试模板短信,根据模板获得内容尚未实现");
                //是否有效  0-失效 1-有效
                entity.setAvailable(1);
                list.add(entity);
            }
            return sysMessagesService.batchInsert(list);
        }
        return result;
    }

    @ApiOperation(value="发送短信信息,根据内容智能匹配模板")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "mobile",value = "要发送的手机号码",dataType = "String", required = true),
            @ApiImplicitParam(name = "msg",value = "发送的内容",dataType = "String", required = true)
    })
    @PostMapping("/sendMsg")
    public Response sendMsg(@RequestParam @Mobile String mobile,@RequestParam String msg){
        //发送类型:single:单发模式;batch:群发模式
        String type="single";
        Response result= smsService.sendMsg(mobile,msg,type,SmsConfig.MSG_API_KEY);
        //如果短信发送成功插入记录
        if(result.isSuccess() || true==true){
            //TODO 计算短信费用

            LocalDateTime expTime= LocalDateTime.now();
            SysMessages entity=new SysMessages();
            //类别  1- 验证类  2-通知类
            entity.setType(2);
            entity.setMobile(mobile);
            entity.setExpiresTime(expTime);
            //TODO 根据模版拼接内容
            entity.setContext(msg);
            //是否有效  0-失效 1-有效
            entity.setAvailable(1);
            return sysMessagesService.insert(entity);
        }
        return result;
    }

	@ApiOperation(value="发送短信信息,根据内容智能匹配模板")
	@ApiImplicitParams({
			@ApiImplicitParam(name = "mobile",value = "要发送的手机号码",dataType = "String", required = true),
			@ApiImplicitParam(name = "msg",value = "发送的内容",dataType = "String", required = true)
	})
	@PostMapping("/sendNoticeMsg")
	public Response sendNoticeMsg(@RequestParam @Mobile String mobile,@RequestParam String msg){
		//发送类型:single:单发模式;batch:群发模式
		String type="single";
		Response result= smsService.sendMsg(mobile,msg,type,SmsConfig.SYS_API_KEY);
		//如果短信发送成功插入记录
		if(result.isSuccess() || true==true){
			//TODO 计算短信费用

			LocalDateTime expTime= LocalDateTime.now();
			SysMessages entity=new SysMessages();
			//类别  1- 验证类  2-通知类
			entity.setType(2);
			entity.setMobile(mobile);
			entity.setExpiresTime(expTime);
			//TODO 根据模版拼接内容
			entity.setContext(msg);
			//是否有效  0-失效 1-有效
			entity.setAvailable(1);
			return sysMessagesService.insert(entity);
		}
		return result;
	}

    @ApiOperation(value="批量发送短信信息,根据内容智能匹配模板")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "mobile",value = "要发送的手机号码,用逗号分割",dataType = "String", required = true),
            @ApiImplicitParam(name = "msg",value = "发送的内容",dataType = "String", required = true),
    })
    @PostMapping("/batchSendMsg")
    public Response batchSendMsg(@RequestParam String mobile,@RequestParam String msg){
        //发送类型:single:单发模式;batch:群发模式
        String type="batch";
        Response result= smsService.sendMsg(mobile,msg,type,SmsConfig.MSG_API_KEY);
        //如果短信发送成功插入记录
        // 测试下无论如何都会写入记录
        if(result.isSuccess() || true==true){
            //TODO 计算短信费用
            List<String> mobileList= Arrays.asList(mobile.split(","));
            List<SysMessages> list=new ArrayList<SysMessages>();
            for (int i=0;i<mobileList.size();i++){
                SysMessages entity=new SysMessages();
                LocalDateTime expTime= LocalDateTime.now();
                //暂时调用idworker
                entity.setId(IdWorker.getId());
                //类别  1- 验证类  2-通知类
                entity.setType(2);
                entity.setMobile(mobileList.get(i));
                entity.setExpiresTime(expTime);
                entity.setSentTime(LocalDateTime.now());
                entity.setContext(msg);
                //是否有效  0-失效 1-有效
                entity.setAvailable(1);
                list.add(entity);
            }
            return sysMessagesService.batchInsert(list);
        }
        return result;
    }

    //TODO 添加 增加模板和修改模板接口

}
